/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-03-26 20:02:45
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-04-18 17:44:50
 * @FilePath: \vite-project\src\components\org\OrgUserInfo.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { ActionType, ProTable } from '@ant-design/pro-components';
import { Button, message, Modal } from 'antd';
import React, { useRef, useState } from 'react';
import OrgUserInfoForm from './OrgUserInfoForm';
import { addUser, delUser, getUserDetail, getUserList, modifyUser } from '@/apis/org';
import CommonDrawer from '../common/CommonDrawer';
import dayjs from 'dayjs';

interface OrgUserInfoProps {
	parentNode?: any;
	treeData?: any[];
}

type TableListItem = {
	id?: string;
};

const OrgUserInfo: React.FC<OrgUserInfoProps> = ({ treeData, parentNode }) => {
	const columns: any[] = [
		{
			title: '用户名',
			key: 'userName',
			dataIndex: 'userName',
		},
		{
			title: '姓名',
			key: 'name',
			dataIndex: 'name',
		},
		{
			title: '手机号',
			key: 'mobile',
			dataIndex: 'mobile',
		},
		{
			title: '性别',
			key: 'sex',
			dataIndex: 'sex',
		},
		{
			title: '创建时间',
			key: 'createTime',
			dataIndex: 'createTime',
			renderText(text: string | number | Date | dayjs.Dayjs | null | undefined) {
				return dayjs(Number(text)).format('YYYY-MM-DD HH:mm:ss');
			},
		},
		{
			title: '最后登录时间',
			key: 'latestLoginTime',
			dataIndex: 'latestLoginTime',
		},
		{
			title: '操作',
			width: 180,
			key: 'option',
			valueType: 'option',
			render: (_: any, record: any) => [
				<a key="link" onClick={() => handleEdit(record)}>
					修改
				</a>,
				<a key="link2" onClick={() => handleDel(record)}>
					删除
				</a>,
			],
		},
	];
	const [open, setOpen] = useState(false);
	const [editFormData, setEditFormData] = useState<API.UserDetailResponseType>();
	const tableRef = useRef<ActionType>();

	const handleEdit = async (record: any) => {
		let res = await getUserDetail({
			id: record.id,
		});
		setOpen(true);
		setEditFormData({
			...res,
			roleIds: res?.roles?.map(item => ({
				application: {
					label: item?.appName,
					value: item?.appId,
				},
				org: {
					label: item?.organizationFullName,
					value: item?.organizationId,
				},
				role: {
					label: item?.roleName,
					value: item?.roleId,
				},
			})),
		});
	};
	const refresh = () => {
		tableRef?.current?.reload?.();
	};
	const handleAdd = () => {
		setOpen(true);
	};
	const handleClose = () => {
		setOpen(false);
	};
	const handleDel = (record: { id: any }) => {
		Modal.confirm({
			title: '提示',
			content: '确定删除用户吗',
			okText: '确定',
			cancelText: '取消',
			centered: true,
			onOk() {
				return new Promise<void>(async (resolve, reject) => {
					try {
						await delUser({
							id: record.id,
						});
						message.success('删除成功');
						resolve();
						refresh();
					} catch (error) {
						reject();
					}
				});
			},
		});
	};
	const onSubmit = async (form: any, closeLoading?: () => void, closeModal?: () => void) => {
		if (editFormData?.id) {
			try {
				await modifyUser({
					id: editFormData?.id,
					organizationId: parentNode.id,
					userName: form?.userName,
					name: form?.name,
					mobile: form?.mobile,
					sex: form?.sex,
					roleIds: form?.roleIds?.map((item: any) => item?.role?.value),
				});
				closeModal?.();
				refresh();
			} finally {
				closeLoading?.();
			}
		} else {
			try {
				await addUser({
					organizationId: parentNode.id,
					userName: form?.userName,
					name: form?.name,
					mobile: form?.mobile,
					sex: form?.sex,
					roleIds: form?.roleIds?.map((item: any) => item?.role?.value),
				});
				closeModal?.();
				refresh();
			} finally {
				closeLoading?.();
			}
		}
	};
	return (
		<>
			<ProTable<TableListItem>
				params={{
					organizationId: parentNode?.id,
				}}
				search={false}
				columns={columns}
				request={async (params, sorter, filter) => {
					let totalPages = 1;
					const res = await getUserList({
						pageNumber: params.current,
						pageSize: params.pageSize,
						organizationId: params.organizationId,
					});
					totalPages = res?.totalRow;
					return {
						data: res?.recordDatas || [],
						success: true,
						total: totalPages,
					};
				}}
				rowKey="id"
				pagination={{
					showQuickJumper: true,
				}}
				dateFormatter="string"
				toolBarRender={() => [
					<Button type="primary" onClick={handleAdd}>
						新建
					</Button>,
				]}
				actionRef={tableRef}
			/>
			<CommonDrawer
				title={`${editFormData?.id ? '编辑' : '新建'}用户`}
				open={open}
				close={handleClose}
				onSubmit={onSubmit}
				initFormData={editFormData}>
				<OrgUserInfoForm treeData={treeData} parentNode={parentNode} close={handleClose} />
			</CommonDrawer>
		</>
	);
};

export default OrgUserInfo;
